package org.come.init;

import com.main.VersionDto;
import org.come.until.GsonUtil;
import org.come.until.NewAESUtil;
import org.json.JSONArray;
import org.json.JSONException;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.come.until.ZipUtils;
import org.come.log.LanderJPanel;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class ClientCheckUpdate
{
    private Boolean needUpdate;
    private Boolean failure;
    private Boolean done;
    private JSONObject jsonObject;
    public static String versionx;
    private UpdateView updateView;
    private VersionDto versionDto;
    public ClientCheckUpdate(final UpdateView updateView) {
        this.needUpdate = Boolean.FALSE;
        this.failure = Boolean.FALSE;
        this.done = Boolean.FALSE;
        this.updateView = updateView;
    }

    public void start() {
        try {
            Thread.sleep(1000L);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        ClientCheckUpdate.versionx = getVersion();
        if (ClientCheckUpdate.versionx != null) {
            //  final String results = Tool.getWebCon("http://127.0.0.1:8083/request/requests888.php?type=CheckUpdate&version=" + ClientCheckUpdate.versionx);
            // String results = Tool.getWebCon("http://127.0.0.1:8083/GameServer/version?version=" + ClientCheckUpdate.versionx);
            String results=null;
            byte[] v = null;
            try {
                v = downloadtxt(new URL("http://81.70.235.33:8088/GameServer/version.json" + "?" + System.currentTimeMillis()));
                try {
                    results=new String(v, NewAESUtil.UTF_8);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            if (results != null) {
                this.jsonObject = Tool.StrintToJson(results);
                if (this.jsonObject != null) {
                    try {
                        String data = jsonObject.getString("data");
                        versionDto =  GsonUtil.getGsonUtil().getgson().fromJson(data, VersionDto.class);
                        ArrayList data1 = (ArrayList)versionDto.getData();
                        if (!data1.get(data1.size()-1).equals(versionx)) {
                            needUpdate = true;
                            if (startUpdate()){
                                updateView.getTitle().setText("更新完成，祝你游戏愉快！");
                                LanderJPanel.getVersion2().setText("更新完成，祝你游戏愉快！");
                                LanderJPanel.kais.setText("更新完成");
                                LanderJPanel.kais.setIcon(new ImageIcon("img/sucai/开始按钮3.png"));
                                LanderJPanel.kais.setBounds(15,18,128,56);
                                LanderJPanel.getVersion1().setText("当前版本：" + ClientCheckUpdate.getVersion());
                                done = true;
                            }else{
                                // updateView.getTitle().setText("更新失败！请到QQ群下载完整版本。");
                                LanderJPanel.getKais().setText("更新失败！请到QQ群下载完整版本。");
                                failure = false;
                                System.exit(1);
                            }
                        } else {
                            LanderJPanel.getVersion2().setText("当前版本是最新版本！");

                            LanderJPanel.kais.setIcon(new ImageIcon("img/sucai/开始按钮3.png"));
                            LanderJPanel.kais.setBounds(15,18,128,56);
                            LanderJPanel.kais.setText("更新完成");
                            LanderJPanel.getVersion1().setText("当前版本：" + ClientCheckUpdate.getVersion());
                            updateView.getTitle().setText("当前版本是最新版本!");
                            done = true;
                        }
                    }
                    catch (JSONException e2) {
                        e2.printStackTrace();
                    }
                }
            }
            else {
                this.failure = Boolean.valueOf(true);
            }
        }
    }

    public Boolean isFailure() {
        return this.failure;
    }

    public Boolean isDone() {
        return this.done;
    }

    public Boolean isNeedUpdate() {
        return this.needUpdate;
    }

    public Boolean startUpdate() {
        if (isNeedUpdate() && updateView!=null) {
            try {
                ArrayList data = (ArrayList)versionDto.getData();
                LanderJPanel.getKais().setIcon(new ImageIcon("img/sucai/下载按钮1.png"));
                LanderJPanel.getKais().setText("更新中");
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).equals(versionx))continue;
                    System.out.println("开始更新"+data.get(i));
                    updateView.getTitle().setText("开始下载更新包:" + data.get(i));
                    //  new UpdatePack((String) );
                    UpdatePack updatePack=new UpdatePack((String) data.get(i), updateView,  1000l);
                    if (!updatePack.start()){
                        LanderJPanel.getKais().setText("更新失败");
                        return false;
                    }
                }
                return true;
            }catch (Exception e){
                e.printStackTrace();
                //System.out.println("检查更新失败！");
                return false;
            }
        }
        return false;
    }

    public static String getVersion() {
        final String cen = Tool.readToString(System.getProperty("user.dir") + "/update/version.json");
        if (cen == null) {
            return null;
        }
        else {
            final JSONObject jsonObject = Tool.StrintToJson(cen);
            if (jsonObject != null && jsonObject.has("version")) {
                try {
                    return jsonObject.getString("version");
                }
                catch (JSONException e) {
                    return null;
                }
            }
            return null;
        }
    }

    public static String getVersionx() {
        return ClientCheckUpdate.versionx;
    }

    public static void setVersionx(final String versionx) {
        ClientCheckUpdate.versionx = versionx;
    }
    public byte[] downloadtxt(URL url) {
        try {
            long x = System.currentTimeMillis();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            InputStream bis = url.openStream();
            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = bis.read(buf)) != -1) {
                bos.write(buf, 0, count);
            }
            bos.close();
            bis.close();
            x = System.currentTimeMillis() - x;
            if (x > 1000) {
                System.err.println("资源下载完毕:耗时" + x);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            System.err.println("下载资源失败 error=" + e.getMessage() + ":" + url.getPath());
            e.printStackTrace();
        }
        return null;
    }
}
